package com.lilidp.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.lilidp.dto.Result;
import com.lilidp.entity.SeckillVoucher;
import com.lilidp.entity.VoucherOrder;
import com.lilidp.mapper.VoucherOrderMapper;
import com.lilidp.service.ISeckillVoucherService;
import com.lilidp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lilidp.utils.RedisIdWorker;
import com.lilidp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 栗顺
 
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Override
    public Result deductStock(Long voucherId) {
        //首先查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //判断优惠券秒杀是否开始
        //
        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        //判断秒杀是否结束
        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        //判断一下库存是否充足
        Integer stock = seckillVoucher.getStock();
        if(stock <=0){
            return Result.fail("优惠券已经抢完");
        }
        //扣减库存，使用cas方法
        //会发生多次失败，因为假设有1000个线程，只有一个能修改成功
//        boolean sucess = seckillVoucherService.update().set("stock", stock - 1)
//                .eq("voucher_id", voucherId)
//                .eq("stock",seckillVoucher.getStock())
//                .update();

        Long userid = UserHolder.getUser().getId();
        synchronized (userid.toString().intern()){
            IVoucherOrderService o = (IVoucherOrderService)AopContext.currentProxy();
            return o.createVoucherOrder(voucherId);
        }

    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //查询数据库，是否有这个订单
        int count = query().eq("voucher_id", voucherId)
                .eq("user_id", UserHolder.getUser().getId()).count();
        if(count > 0){
            return Result.fail("已经抢购过了");
        }

        //扣减库存，使用cas方法
        boolean sucess = seckillVoucherService.update().setSql("stock=stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)
                .update();
        if(!sucess){
            return Result.fail("扣减失败");
        }
        long orderid= redisIdWorker.nextId("order");
        //生成订单
        VoucherOrder voucherOrder=new VoucherOrder().
                setId(orderid)
                .setVoucherId(voucherId)
                .setUserId(UserHolder.getUser().getId());
        save(voucherOrder);
        return Result.ok(orderid);
    }

}
